<?php
namespace app\site\service;

use app\common\library\Service;

class SiteOperate extends Service
{
    use \app\common\library\traits\Model;
    protected $batchValidate = null;
    protected $modelValidate = null;

	protected function _initialize() {
        parent::_initialize();
		$this->model = model('site/SiteOperate');
    }
    /**
     * 站点列表
     * @param mixed $maps   查询条件
     * @return mixed
     */
    public function lists($maps = '', $order = 'create_time DESC', $page = 0, $limit = 12, $field = true, $relations = [], $attrs =[]) {
        $result = $this->model->order($order)->field($field);
        if (isset($maps['site_id'])) {
            $result = $result->where('site_id','=',$maps['site_id']);
        }
        if($page !== false) {
            $result = $result->paginate($limit, '', ['page' => $page]);
        } else {
            $result = $result->limit($limit)->select();
        }

        /* 关联数据获取 */
        if(!empty($relations)) {
            foreach ($result as $key => $value) {
                array_map(function($e) use (&$value) {
                    $e = trim($e);
                    $value->$e = $value->$e ?: new \stdClass(); // 注意没有数据不要返回默认的 NULL
                }, $relations);
            }
        }

        /* 获取器数据 */
        if(!empty($attrs)) {
            foreach ($result as $key => $value) {
                array_map(function($attr) use (&$value) {
                    $attr = trim($attr);
                    return $value->$attr = $value->getAttr($attr);
                }, $attrs);
            }
        }
        return $result;
    }
    /**
     * [detail 详情]
     * @param  string $site_id [description]
     * @return [type]          [description]
     */
    public function detail($site_id = ''){

    }
    /**
     * [create description]
     * @param  string  $site_id [description]
     * @param  string  $action  [description]
     * @param  string  $unit    [description]
     * @param  integer $number  [description]
     * @param  string  $cost    [description]
     * @return [type]           [description]
     */
    public function create($site_id = '',$action = '',$custom_id = 0,$unit = '',$number = 0,$log_id = 0){
        $info = [
            'site_id' => $site_id,
            'action' => $action,
            'unit' => $unit,
            'number' => $number,
            'log_id' => $log_id,
            'custom_id' => $custom_id
        ];
        \Db::startTrans();
        try{
            $result = $this->model->create($info,false);
        }catch(\Exception $e){
            $this->error = $e->getMessage();
            \Db::rollback();
            return false;
        }
        \Db::commit();
        return $result;
    }
}